import { getCurrentInstance, reactive } from 'vue';
import type { ILeftAside, ILeftAsideConfigItemPublic, ILeftAsideConfigItem } from './types';
import { ElMessage } from 'element-plus';
import { svgToSymbol } from '../utils';
import { configStore } from './config';

// 动态导入所有SVG文件并分类
const importAndCategorizeAllSvgs = () => {
  try {
    // 重新启用SVG动态导入
    const svgContext = import.meta.glob('/src/assets/svgs/*.svg', {
      as: 'raw',
      eager: true
    });
    const svgUrlContext = import.meta.glob('/src/assets/svgs/*.svg', {
      as: 'url',
      eager: true
    });

    const categories: { [key: string]: ILeftAsideConfigItemPublic[] } = {
      特效动画: [],
      背景装饰: [],
      阀门组件: []
    };

    Object.entries(svgContext).forEach(([path, svgContent]) => {
      const filename = path.split('/').pop()?.replace('.svg', '') || '';
      const svgUrl = svgUrlContext[path] as string;

      // 确定分类
      let category = '特效动画'; // 默认分类
      if (filename.includes('special-effect')) {
        category = '特效动画';
      } else if (filename.includes('bg-')) {
        category = '背景装饰';
      } else if (filename.includes('valve')) {
        category = '阀门组件';
      }

      // 生成友好的显示名称
      const displayName =
        filename
          .replace(/special-effect/, '特效')
          .replace(/bg-/, '背景')
          .replace(/valve/, '阀门')
          .replace(/^\d+/, '') // 移除前导数字
          .replace(/[-_]/g, ' ') // 替换连字符和下划线为空格
          .trim() || filename;

      const svgItem: ILeftAsideConfigItemPublic = {
        id: `svg-${filename}`,
        type: 'svg' as const,
        title: displayName,
        thumbnail: svgUrl, // 使用URL作为缩略图
        svg: svgContent as string, // 使用SVG内容字符串用于symbol转换
        props: {
          fill: { type: 'color', val: '#409eff', title: '填充颜色' },
          stroke: { type: 'color', val: '#ffffff', title: '边框颜色' },
          strokeWidth: { type: 'input', val: '1', title: '边框宽度' },
          opacity: {
            type: 'slider',
            val: 1,
            title: '透明度',
            options: { min: 0, max: 1, step: 0.1 }
          }
        }
      };

      categories[category].push(svgItem);
    });

    return categories;
  } catch (error) {
    console.warn('SVG导入失败，使用空的分类配置:', error);
    return {
      特效动画: [],
      背景装饰: [],
      阀门组件: []
    };
  }
};

// 创建SVG组件分类配置
const svgCategories = importAndCategorizeAllSvgs();

// 创建图表组件配置（从系统组件中过滤）
const chartComponents = configStore.sysComponent.filter((item) => item.id.startsWith('echart-'));
// 创建非图表系统组件配置
const systemComponents = configStore.sysComponent.filter((item) => !item.id.startsWith('echart-'));

// 转换SVG组件为内部配置格式的辅助函数
const convertSvgToConfigItem = (svgItems: ILeftAsideConfigItemPublic[]): ILeftAsideConfigItem[] => {
  return svgItems.map((m) => {
    if (m.type === 'svg') {
      const { symbol_str, width, height } = svgToSymbol(m.svg!, m.id);
      return {
        ...m,
        symbol: {
          symbol_id: m.id,
          symbol_str,
          width,
          height
        },
        common_animations: {
          val: '',
          delay: 'delay-0s',
          speed: 'slow',
          repeat: 'infinite'
        }
      };
    }
    return {
      ...m,
      common_animations: {
        val: '',
        delay: 'delay-0s',
        speed: 'slow',
        repeat: 'infinite'
      }
    };
  });
};

export const leftAsideStore: ILeftAside = reactive({
  config: new Map<string, ILeftAsideConfigItem[]>([
    ['本地文件', []],
    ['系统组件', systemComponents],
    ['图表组件', chartComponents],
    ['特效动画', convertSvgToConfigItem(svgCategories['特效动画'] || [])],
    ['背景装饰', convertSvgToConfigItem(svgCategories['背景装饰'] || [])],
    ['阀门组件', convertSvgToConfigItem(svgCategories['阀门组件'] || [])]
  ]),
  registerConfig: (title: string, config: ILeftAsideConfigItemPublic[]) => {
    const reservedTitles = ['本地文件', '系统组件', '图表组件', '特效动画', '背景装饰', '阀门组件'];
    if (reservedTitles.includes(title)) {
      ElMessage.info(`title:${title}已被系统占用，请更换名称！`);
      return;
    }

    if (leftAsideStore.config.has(title)) {
      ElMessage.info(`title:${title}已存在，已经将其配置覆盖`);
    }
    const cfg: ILeftAsideConfigItem[] = config.map((m) => {
      if (m.type == 'svg') {
        const { symbol_str, width, height } = svgToSymbol(m.svg!, m.id);
        return {
          ...m,
          symbol: {
            symbol_id: m.id,
            symbol_str,
            width,
            height
          },
          common_animations: {
            val: '',
            delay: 'delay-0s',
            speed: 'slow',
            repeat: 'infinite'
          }
        };
      }
      return {
        ...m,
        common_animations: {
          val: '',
          delay: 'delay-0s',
          speed: 'slow',
          repeat: 'infinite'
        }
      };
    });
    leftAsideStore.config.set(title, cfg);
  }
});
